package org.ricks.lambda.methodhandle;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class MethodHandleLoader {
    private static final Map<Method, MethodHandle> handleCache = new ConcurrentHashMap<>();

    public static MethodHandle getHandle(Object instance, Method method) throws Throwable {
        return handleCache.computeIfAbsent(method, m -> {
            MethodHandles.Lookup lookup = MethodHandles.lookup();
            try {
                return lookup.unreflect(method).bindTo(instance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
    }

    // 扫描类中带有@DynamicMethod注解的方法
    public static List<Method> scanAnnotatedMethods(Class<?> clazz) {
        return Arrays.stream(clazz.getDeclaredMethods())
                .filter(m -> m.isAnnotationPresent(DynamicMethod.class))
                .collect(Collectors.toList());
    }
}
